#include "ListenAccept.h"
#include "Channel.h"

ListenAccept::ListenAccept(ACE_Reactor* act)
{
    this->reactor(act);
}


ListenAccept::~ListenAccept()
{
   
}

int ListenAccept::open(int port)
{
    ACE_INET_Addr port_to_listen(port);
    if ( this->m_objAcceptor.open(port_to_listen,100) == -1 ) 
    {
        printf("ListenAccept::open() ERROR [port:%d]\n",port);
        return -1;
    }
    else
    {
         printf("Listening on [port:%d]\n",port);
    }
    return this->reactor()->register_handler(this, ACE_Event_Handler::ACCEPT_MASK);
}

ACE_HANDLE ListenAccept::get_handle (void) const
{
    return this->m_objAcceptor.get_handle();
}

int ListenAccept::handle_input(ACE_HANDLE fd)
{
    Channel * ch = new Channel();

    if (this->m_objAcceptor.accept(ch->m_socketStream) == -1) 
    {
        printf("ListenAccept::handle_input() ERROR\n");
		delete ch;
        return -1;
    }
	else
	{
		printf("Accepted [handler:%d]\n",ch->m_socketStream.get_handle());
	}

    if (this->reactor()->register_handler(ch, ACE_Event_Handler::READ_MASK) == -1 )
    {
        printf("ListenAccept::handle_input() register_handler ERROR\n");
		delete ch;
        return -1;
    }

    return 0;
}

